import json
from files import *
from DictTxt import DictTxt
from Convertor import PinyinConvertor
from Convertor import RegCodeConvertor


class Schema:
    """
    Rime 输入方案
    """

    def __init__(self, config_file) -> None:
        super().__init__()
        self.config_file = config_file
        self.sources = []
        self.base_dir = ''
        self.dist_dir = 'dist'
        self.convertor = None
        self.dicts = []
        self._load()

    def build(self):
        print('build')
        print(f'base_dir={self.base_dir}')
        print(f'sources={self.sources}')
        print(f'dist_dir={self.dist_dir}')
        delete_dir(self.dist_dir)
        make_dirs(self.dist_dir)
        self._handle_sources()
        self._handle_dicts()

    def _load(self):
        file_must_exist(self.config_file)
        self.base_dir = normalize_path(self.config_file, '..')
        self.dist_dir = normalize_path(self.base_dir, '../dist')
        with open_utf8_read(self.config_file) as f:
            print(f'load config file: {self.config_file}')
            json_obj = json.load(f)
            for source in json_obj.get('sources'):
                self.sources.append(normalize_path(self.base_dir, source))
            self.dicts = json_obj.get('dicts')
            if 'pinyin_convertor' in json_obj:
                config = json_obj.get('pinyin_convertor')
                self.convertor = PinyinConvertor(config.get('sheng'), config.get('yun'), config.get('special'))
            elif 'reg_code_convertor' in json_obj:
                rules = json_obj.get('reg_code_convertor')
                self.convertor = RegCodeConvertor(rules)

    def _handle_sources(self):
        for source in self.sources:
            name = filename_of(source)
            if is_file(source):
                copy_file(source, normalize_path(self.dist_dir, name))
            elif is_dir(source):
                copy_dir(source, normalize_path(self.dist_dir, name))

    def _handle_dicts(self):
        for item in self.dicts:
            dict_source = normalize_path(self.base_dir, item.get('source'))
            aux_source = normalize_path(self.base_dir, item.get('aux_source'))
            print(f'handle dict source: {dict_source}')
            dict_txt = DictTxt()
            if 'aux_for_words_length' in item:
                dict_txt.set_aux_for_words_length(item.get('aux_for_words_length'))
            if 'convert_first' in item:
                dict_txt.set_convert_first(item.get('convert_first'))
            if self.convertor:
                dict_txt.convert(dict_source, self.convertor, aux_source, item.get('aux_length'))
            else:
                dict_txt.convert(dict_source, None, aux_source)
            dict_txt.write_yaml(normalize_path(self.dist_dir, item.get('name')))
